package cn.tuzirpa.manager;

import cn.tuzirpa.config.DatabaseConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库管理器
 * 负责数据库连接、检测数据库是否存在、创建数据库等功能
 */
public class DatabaseManager {
    
    private static final Logger logger = LoggerFactory.getLogger(DatabaseManager.class);
    
    private final DatabaseConfig config;
    
    public DatabaseManager(DatabaseConfig config) {
        this.config = config;
    }
    
    /**
     * 检测数据库是否存在
     */
    public boolean databaseExists() {
        try (Connection connection = getBaseConnection()) {
            // 使用SHOW DATABASES命令来检测数据库是否存在
            String sql = "SHOW DATABASES LIKE ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, config.getDatabaseName());
                try (ResultSet resultSet = statement.executeQuery()) {
                    boolean exists = resultSet.next();
                    if (exists) {
                        logger.info("数据库 {} 已存在", config.getDatabaseName());
                    } else {
                        logger.info("数据库 {} 不存在", config.getDatabaseName());
                    }
                    return exists;
                }
            }
        } catch (SQLException e) {
            logger.error("检测数据库是否存在时发生错误", e);
            throw new RuntimeException("检测数据库是否存在失败", e);
        }
    }
    
    /**
     * 创建数据库
     */
    public void createDatabase() {
        if (databaseExists()) {
            logger.info("数据库 {} 已存在，跳过创建", config.getDatabaseName());
            return;
        }
        
        String createDatabaseSql = String.format(
            "CREATE DATABASE `%s` CHARACTER SET %s COLLATE %s",
            config.getDatabaseName(),
            config.getCharset(),
            config.getCollation()
        );
        
        try (Connection connection = getBaseConnection();
             Statement statement = connection.createStatement()) {
            
            statement.execute(createDatabaseSql);
            logger.info("成功创建数据库: {}", config.getDatabaseName());
            
        } catch (SQLException e) {
            logger.error("创建数据库失败: {}", config.getDatabaseName(), e);
            throw new RuntimeException("创建数据库失败", e);
        }
    }
    
    /**
     * 获取数据库连接（包含数据库名）
     */
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(
            config.getFullUrl(),
            config.getUsername(),
            config.getPassword()
        );
    }
    
    /**
     * 获取基础连接（不包含数据库名）
     */
    public Connection getBaseConnection() throws SQLException {
        return DriverManager.getConnection(
            config.getBaseUrl(),
            config.getUsername(),
            config.getPassword()
        );
    }
    
    /**
     * 测试数据库连接
     */
    public boolean testConnection() {
        try (Connection connection = getConnection()) {
            return connection.isValid(5);
        } catch (SQLException e) {
            logger.error("数据库连接测试失败", e);
            return false;
        }
    }
    
    /**
     * 测试基础连接
     */
    public boolean testBaseConnection() {
        try (Connection connection = getBaseConnection()) {
            return connection.isValid(5);
        } catch (SQLException e) {
            logger.error("基础数据库连接测试失败", e);
            return false;
        }
    }
    
    /**
     * 关闭数据源（JDBC连接池不需要手动关闭）
     */
    public void close() {
        logger.info("数据库管理器已关闭");
    }
    
    /**
     * 获取数据库配置信息
     */
    public DatabaseConfig getConfig() {
        return config;
    }
}
